import fs from 'fs-extra'
import path from 'path'
import { Todo, Group, Tag } from '@data/index'

// 数据存储路径
const DATA_DIR = path.resolve('./data')
const TODOS_FILE = path.join(DATA_DIR, 'todos.json')
const GROUPS_FILE = path.join(DATA_DIR, 'groups.json')
const TAGS_FILE = path.join(DATA_DIR, 'tags.json')

// 确保数据目录存在
async function ensureDataDir() {
  await fs.ensureDir(DATA_DIR)
}

// 通用数据操作类
class DataStore<T extends { id: string }> {
  private filePath: string
  private cache: T[] | null = null

  constructor(filePath: string) {
    this.filePath = filePath
  }

  // 读取数据
  async load(): Promise<T[]> {
    if (this.cache) {
      return this.cache
    }

    await ensureDataDir()

    try {
      if (await fs.pathExists(this.filePath)) {
        const data = await fs.readJson(this.filePath)
        this.cache = Array.isArray(data) ? data : []
      } else {
        this.cache = []
        await this.save()
      }
    } catch (error) {
      console.error(`Error loading data from ${this.filePath}:`, error)
      this.cache = []
    }

    return this.cache
  }

  // 保存数据
  async save(): Promise<void> {
    if (this.cache === null) {
      return
    }

    try {
      await fs.writeJson(this.filePath, this.cache, { spaces: 2 })
    } catch (error) {
      console.error(`Error saving data to ${this.filePath}:`, error)
      throw error
    }
  }

  // 获取所有数据
  async findAll(): Promise<T[]> {
    return await this.load()
  }

  // 根据ID查找
  async findById(id: string): Promise<T | undefined> {
    const data = await this.load()
    return data.find((item) => item.id === id)
  }

  // 创建数据
  async create(item: T): Promise<T> {
    const data = await this.load()
    data.push(item)
    this.cache = data
    await this.save()
    return item
  }

  // 更新数据
  async update(id: string, updates: Partial<T>): Promise<T | null> {
    const data = await this.load()
    const index = data.findIndex((item) => item.id === id)

    if (index === -1) {
      return null
    }

    data[index] = { ...data[index], ...updates }
    this.cache = data
    await this.save()
    return data[index]
  }

  // 删除数据
  async delete(id: string): Promise<boolean> {
    const data = await this.load()
    const index = data.findIndex((item) => item.id === id)

    if (index === -1) {
      return false
    }

    data.splice(index, 1)
    this.cache = data
    await this.save()
    return true
  }

  // 批量更新
  async bulkUpdate(updates: { id: string; data: Partial<T> }[]): Promise<void> {
    const data = await this.load()

    updates.forEach(({ id, data: updateData }) => {
      const index = data.findIndex((item) => item.id === id)
      if (index !== -1) {
        data[index] = { ...data[index], ...updateData }
      }
    })

    this.cache = data
    await this.save()
  }

  // 清空缓存
  clearCache(): void {
    this.cache = null
  }
}

// 具体的数据存储实例
export const todoStore = new DataStore<Todo>(TODOS_FILE)
export const groupStore = new DataStore<Group>(GROUPS_FILE)
export const tagStore = new DataStore<Tag>(TAGS_FILE)

// 初始化数据存储
export async function initializeDataStore() {
  await ensureDataDir()

  // 预加载所有数据
  await Promise.all([todoStore.load(), groupStore.load(), tagStore.load()])

  console.log('Data store initialized')
}
